<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class WechatLoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    public $openid;
    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    public function validateWechatInfo()
    {
        $wechatInfo = Yii::$app->session->get('wechatInfo');
        if (isset($wechatInfo['subscribe']) && ($wechatInfo['subscribe'] == 1)) {
            return true;
        } else {
            return false;
        }
    }

    /** 3600*24*30
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login($openid)
    {
        if ($this->validateWechatInfo()) {
            // var_dump($this->getUser());die;
            return Yii::$app->user->login($this->getUser(), 0);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = WechatUser::findBySession();
        }    
           
        return $this->_user;
    }
}
